package org.melanesia.beans;

import java.util.List;

class CompositeGetter implements Getter {

	private List<PropertyAccessor> propertyAccessorList;
    
	CompositeGetter(List<PropertyAccessor> propertyAccessorList) {
		this.propertyAccessorList = propertyAccessorList;
	}
	
	@Override
	public Object get(Object bean) {
		
	    Object result = null;
	    
        for (int i = 0, size = propertyAccessorList.size(); i < size; i++) {
            
            PropertyAccessor accessor = propertyAccessorList.get(i);
            
            if (i+1 == size) {
                
                // Last property in chain
                result = accessor.get(bean);
                
            } else {
                
                // Intermediate property
                Object subBean = accessor.get(bean);
                if (subBean == null) {
                    return null;
                }
                
                bean = subBean;
            }
        }
        
        return result;
	}

	@Override
	public Class<?> getReturnType() {
		return propertyAccessorList.get(propertyAccessorList.size() - 1).getPropertyClass();
	}
	
}
